#!/usr/bin/env python3
#-*-coding:utf-8-*-
import os
import sys

def install():
	#检查jdk是否已经安装
	cmd = 'which java'
	res = os.popen(cmd).read().strip("\n")
	java_bin = '/usr/local/jdk1.8.0_181/bin/java'
	if res != java_bin:
		print("jdk未安装，请检查")
		sys.exit(1)
	#切换目录至/data
	os.chdir('/data')
	#下载tomcat，默认版本为8.5.46
	cmd = "curl -O https://mirrors.tuna.tsinghua.edu.cn/apache/tomcat/tomcat-8/v8.5.46/bin/apache-tomcat-8.5.46.tar.gz"
	res = os.system(cmd)
	if res != 0:
		print("下载失败，请重试")
		sys.exit(1)

	#解压
	cmd = "tar -xzvf apache-tomcat-8.5.46.tar.gz"
	res = os.system(cmd)
	res = os.system(cmd)
	if res != 0:
		print("解压失败，请重试")
		sys.exit(1)
	
	#创建代码备份目录以及存放目录
	os.chdir('apache-tomcat-8.5.46')
	os.mkdir('backup', 0755)
	os.mkdir('wars', 0755)

	#清理webapps目录下的文件
	cmd = "rm -rf webapps/*"
	os.system(cmd)
	
	#tomcat重启脚本
	f = open("./restart.sh", mode="w")
	f.write("""#!/bin/bash/
TOMCAT_BIN=/data/apache-tomcat-8.5.46/bin
${TOMCAT_BIN}/shutdown.sh
sleep 5
pid=`ps aux | grep tomcat | grep -v grep | awk '{print $2}'`
kill -9 $pid && echo "Tomcat process [$pid] was killed ...."
sleep 5
${TOMCAT_BIN}/startup.sh""")
	f.close()
	#给予执行权限
	os.chmod("./restart.sh", 0755)

if __name__ == "__main__":
	install()	
